/**
 * api-report.html page script
 * @author czp
 * date : 2014-04-11
 */
var defDay = 30;
var nowDay = new Date().format("yyyy-MM-dd hh:mm:ss");
var startDay = new Date( new Date() - defDay*24*3600*1000 ).format("yyyy-MM-dd hh:mm:ss");
var timeRange = startDay + " > " + nowDay;
$('input[name="datePicker"]').val(timeRange);
var autoHeight = window.innerHeight - 290;
var tab = "#apiCountItemTab";
var page = "#apiCountItemPage";
var appSelect = "#appSelect";
var apiSelect = "#apiSelect";
var items = "#apiCountTab";
init();
refApiCount(timeRange, null, null);

function refApiCount(time, appName, apiName) {
    $.ajax({
        url: contextPath + '/report/apiCountRep',
        type: 'POST',
        data: {"time_range": time, "appName" : appName, "apiName" : apiName},
        success: function (data) {
            var html_items = "";
            var apiNames = data.apis;
            var table_tr = [];
            var api = "";
            var count = 0;
            for (var key in data.map) {
                for (var i = 0; i < data.map[key].length; i++) {
                    api = apiNames[i];
                    count = data.map[key][i];
                    if (count !== 0) {
                        table_tr.push({
                            "appName" : key,
                            "apiName" : api,
                            "count" : count
                        })
                    }
                }
            }
            table_tr.forEach(function (m) {
               html_items +=
                   "<tr>\n" +
                   "  <td class='center'>" + m.appName + "</td>\n" +
                   "  <td class='center'>" + m.apiName + "</td>\n" +
                   "  <td class='center'>" + m.count + "</td>\n" +
                   "  <td class='center'><div class='blue' id='gritter-center' " +
                   "   onclick='getCharts(\""+ m.appName + "\",\"" + m.apiName +"\")' href='#'>" +
                   "  <i class = 'icon-zoom-in bigger-130'></i></div></td>\n" +
                   "</tr>";
            });
            $(items).html(html_items);
        }
    })
}

function init() {
    getAppItems();
    getApiItems();
}

function getAppItems() {
    $.ajax({
        url : contextPath + '/report/getAppNames',
        type : 'POST',
        success : function(data) {
            $(appSelect).append("<option value=\"" + " " + "\">" + " " + "</option>");
            for (var i = 0; i < data.length; i++) {
                $(appSelect).append("<option value=\"" + data[i] + "\">" + data[i] + "</option>");
            }
        }
    });
}

function getApiItems() {
    $.ajax({
        url : contextPath + '/report/getApiNames',
        type : 'POST',
        success : function(data) {
            $(apiSelect).append("<option value=\"" + " " + "\">" + " " + "</option>");
            for (var i = 0; i < data.length; i++) {
                $(apiSelect).append("<option value=\"" + data[i] + "\">" + data[i] + "</option>");
            }
        }
    });
}

$("#rest").on('click', function () {
    $('input[name="datePicker"]').val(timeRange);
    $(appSelect).val("");
    $(apiSelect).val("");
});

$("#find").on('click', function () {
    var time = $('input[name="datePicker"]').val();
    var appName = $(appSelect).val();
    var apiName = $(apiSelect).val();
    refApiCount(time, appName, apiName);
});

function getCharts(app, api) {
    // console.log("app:" + app + "\napi:" + api);
    var times = $('input[name="datePicker"]').val();
    $.ajax({
        url : contextPath + '/report/apiCountCharts',
        type : 'POST',
        data : {
            "appName" : app,
            "apiName" : api,
            "time_range" : times
        },
        success: function (data) {
            var _data = [];
            var map = [];
            var xAxisBuf = printDay(times, ">");
            for (var i = 0; i < data.buckets.length; i++) {
                map.push({
                    "key" : data.buckets[i].key_as_string,
                    "val" : data.buckets[i].doc_count
                })
            }
            for (i = 0; i < xAxisBuf.length; i++) {
                _data[i] = 0;
                map.forEach(function (m) {
                    if (m.key === xAxisBuf[i]) {
                        _data[i] = m.val;
                    }
                })
            }
            $("#barDialog").removeClass('hide').dialog({
                modal : true,
                height: 0.61 * (autoHeight + 200),
                width : (autoHeight + 200),
                "class" : "btn btn-xs",
                buttons : [{
                    text : "关闭",
                    click : function() {
                        $(this).dialog("close");
                    }
                }]
            });
            $("#bar").height(0.61 * (autoHeight));
            var option = {
                title: {
                    text: '【 ' + app + " > " + api + ' 】访问统计'
                },
                color: ['#3398DB'],
                tooltip : {
                    trigger: 'axis',
                    axisPointer : {
                        type : 'shadow'
                    }
                },
                toolbox: {
                    show : true,
                    feature : {
                        mark : {show: true},
                        dataView : {show: true, readOnly: false},
                        magicType : {show: true, type: ['line', 'bar']},
                        restore : {show: true},
                        saveAsImage : {show: true}
                    }
                },
                dataZoom: [{
                    type: 'inside'
                }],
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis : [{
                    type : 'category',
                    data : xAxisBuf,
                    axisTick: {
                        alignWithLabel: true
                    }
                }],
                yAxis : [{
                    type : 'value'
                }],
                series : [{
                    name:'访问次数',
                    type:'line',
                    barWidth: '60%',
                    data: _data
                }]
            };
            var myChart = echarts.init(document.getElementById('bar'));
            myChart.setOption(option);
        }
    });
}
